<script setup lang="ts">

import {onMounted, ref} from "vue";
import {deleteStudent, getStuList} from "../../apis/StudentApi.ts";
import {ElMessage} from "element-plus";
import {Student} from "../../types";
import { Search } from '@element-plus/icons-vue'
import StudentForm from "../../components/StudentForm.vue";
import * as XLSX from 'xlsx'
import {getDepById} from "../../apis/DepartmentApi.ts";
import {getClassroomById, getClassroomList} from "../../apis/ClassroomApi.ts";

const studentList = ref<Array<Student>>([])
const search = ref<string>('')
const showForm = ref(false)
const studentForm = ref<Student>()

const openForm = (type:string,student?:Student) => {
    showForm.value = true
    if (type === 'add'){
        studentForm.value = {}
    }
    if (type === 'update'){
        console.log('update student',student)
        studentForm.value = student
    }
}

const getStuListData = async () => {
    let res = await getStuList();
    if (res.flag){
        studentList.value = res.data;
        for(let i = 0;i<studentList.value.length;i++){
            let depRes = await getDepById(studentList.value[i].departmentId);
            studentList.value[i].departmentName = depRes.data.name
            let classRes = await getClassroomById(studentList.value[i].classId);
            studentList.value[i].className = classRes.data.name
        }

    }else{
        ElMessage.error(res.msg)
    }
}

const deleteRow = async (student: Student) => {
    let res = await deleteStudent(student.id);
    if (res.flag){
        ElMessage.success(res.msg)

    }
    await getStuListData()
}

const searchStudent = async () => {
    let res = await getStuList(search.value);
    if (res.flag){
        studentList.value = res.data;
    }else{
        ElMessage.error(res.msg)
    }
}

const exportExcel = async () => {
    // 自定义表头
    const customHeader = [
        {label: "学号", key: "id"},
        {label: "账号", key: "account"},
        {label: "密码", key: "password"},
        {label: "姓名", key: "name"},
        { label: "邮箱", key: "email" },
        { label: "电话", key: "phone" },
        { label: "班级", key: "className" },
        { label: "地址", key: "address" },
        { label: "院系", key: "departmentName" },
        { label: "最近登录时间", key: "loginTime" }

    ];

    let res = await getStuList();

    if (res.flag){
        for(let i = 0;i<res.data.length;i++){
            let depRes = await getDepById(res.data[i].departmentId);
            res.data[i].departmentName = depRes.data.name
            let classRes = await getClassroomById(res.data[i].classId);
            res.data[i].className = classRes.data.name
        }
        let data = res.data;
        // 使用自定义表头映射数据
        const headerMappedData = data.map(item => {
            return customHeader.reduce((acc, curr) => {
                acc[curr.label] = item[curr.key];
                return acc;
            }, {});
        });

        let ws = XLSX.utils.json_to_sheet(headerMappedData, {header: customHeader.map(h => h.label)});
        let wb = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, ws, "学生信息");

        XLSX.writeFile(wb, "学生信息.xlsx");
    }else{
        ElMessage.error(res.msg)
    }
}

onMounted(async () => {
    await getStuListData();
})



</script>

<template>

    <el-row :gutter="20">
        <el-col :span="16">
<!--            搜索框-->
            <el-input
                v-model="search"
                style="width: 340px"
                placeholder="搜索学生"
                :prefix-icon="Search"
            />
            <el-button type="primary" style="margin-left: 20px;"   @click="searchStudent">搜索</el-button>
            <el-button type="primary"    @click="openForm('add')">添加学生</el-button>
            <el-button type="primary"    @click="getStuListData">刷新</el-button>
            <el-button type="success"  @click="exportExcel">导出Excel</el-button>
        </el-col>
        <el-col :span="8">

        </el-col>
    </el-row>
    <br>

    <div class="table-container">
        <el-table :data="studentList" stripe class="stu-table" border >
            <el-table-column prop="id" label="ID" width="130" />
            <el-table-column prop="account" label="账号" width="100" />
            <el-table-column prop="password" label="密码" width="110" />
            <el-table-column prop="name" label="姓名" width="100" />
            <el-table-column prop="email" label="邮箱" width="170" />
            <el-table-column prop="phone" label="电话" width="140" />
            <el-table-column prop="departmentName" label="院系" width="120" />
            <el-table-column prop="className" label="班级" width="120" />
            <el-table-column prop="address" label="地址" width="140" />

            <el-table-column prop="loginTime" label="最近登录时间" width="170"/>
            <el-table-column label="操作" width="160" fixed="right">
                <template #default="scope">
                    <el-button type="primary"   @click="openForm('update',scope.row)">编辑</el-button>
                    <el-popconfirm title="确认删除？" @confirm="deleteRow(scope.row)">
                        <template #reference>
                            <el-button type="danger"  >删除</el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
    </div>
    <el-dialog v-model="showForm" v-if="showForm" title="修改个人信息" width="500">
        <StudentForm :data="studentForm" @handler="showForm = false;getStuListData()"/>
    </el-dialog>
</template>

<style scoped>
.stu-table{
    width: 100%;
    overflow: auto;
}
.table-container {
    width: max-content; /* 或者 fit-content, 使容器仅包裹内容 */
    display: inline-block; /* 使容器能够收缩至内容宽度 */
    overflow-x: auto; /* 添加滚动条，以防内容超出可视区域 */
}
</style>